package com.papper.common.mq.redis;

import com.alibaba.fastjson.JSONObject;
import com.papper.common.bean.base.BaseMqEvent;
import com.papper.common.cache.CacheConstants;
import com.papper.common.cache.redis.RedisCache;
import com.papper.common.config.PapperStorage;
import com.papper.common.service.base.BaseMqEventService;
import com.papper.common.service.log.LogEmailService;
import com.papper.common.utils.tool.DateTool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service("redisCacheMqService")
public class RedisCacheMqService {
    private static final Logger logger        = LoggerFactory.getLogger(RedisCacheMqService.class);
    private static       Date   LastSendEmail = new Date();

    @Autowired
    RedisCache         cache;
    @Autowired
    BaseMqEventService mqEventService;
    @Autowired
    LogEmailService    logEmailService;

    public void producerEvent(String group, String data) {
        BaseMqEvent mqEvent = mqEventService.findByEvent(group);
        if (mqEvent == null) {
            mqEvent = mqEventService.createEvent(group);
        }
        String     key        = CacheConstants.Keys(CacheConstants.REDIS_MQ, mqEvent == null ? 1 : mqEvent.getMqGroup());
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("group", group);
        jsonObject.put("data", data);
        try {
            Long rtn = cache.lpush(key, jsonObject.toJSONString());
            logger.error("任务入库:[{}],[{}]", key, jsonObject.toJSONString());
            if (rtn >= 100 && rtn % 100 == 0) {
                failEmail(rtn, group);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("任务入库异常:[{}].[{}].[{}]", jsonObject.toJSONString(), e.getMessage());
        }
    }

    public String consumerEvent(String db, int timeOut) {
        String key = CacheConstants.Keys(CacheConstants.REDIS_MQ, db);
        try {
            String rtn = cache.brpop(key, timeOut);
            return rtn;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("任务消费异常:[{}].[{}].[{}]", db, e.getMessage());
        }
        return null;
    }

    private void failEmail(Long count, String msg) {
        if (DateTool.getNumberOfMinuteBetween(LastSendEmail, new Date()) < 40) {
            return;
        }
        // 订单分润异常
        StringBuffer content = new StringBuffer();
        content.append("任务系统堵塞").append(":[");
        content.append(msg);
        content.append("]");
        content.append("[");
        content.append(count);
        content.append("]");
        content.append("[");
        content.append(PapperStorage.System().getSystemHost()).append(":").append(PapperStorage.System().getSystemPort());
        content.append("]");
        content.append("[");
        content.append(PapperStorage.System().getSystemName());
        content.append("]");
        String from = PapperStorage.Config("SysMailSendConfig", "mail.default.from", "jnsh@hzjieniu.com");
        String to   = PapperStorage.Config("EmailGroup", "jserror.send.email", "115095375@qq.com");
        LastSendEmail = new Date();
        logEmailService.sendEmail(from, to, "任务系统堵塞", content.toString(), null);
    }
}
